import { defineStore } from 'pinia'
import { dictState, Dict } from '../types'
import STORE_NAMES from '../store-names'
import { dictDataService } from '@gyk/gyk-api'


const useDictStore = defineStore(STORE_NAMES.DICT, {
  state: (): dictState => {
    return {
      dictMap: new Map<string, Dict[]>()
    }
  },
  getters: {

  },
  actions: {
    async dicts(types: string[]): Promise<Map<string, Dict[]>> {
      const resultDicts = new Map<string, any>()
      const allPromise: any[] = []
      // 遍历所有的types
      for (let i in types) {
        const type = types[i]
        if (this.dictMap.has(type)) {
          resultDicts.set(type, this.dictMap.get(type))
        }else {
          const query = { dictType: type }
          allPromise.push(dictDataService.getDicts(query))
        }
      }
      await Promise.all(allPromise).then(results => {
        for (let i in results) {
          const res = results[i]
          const data = res.data
          if (data && data.length > 0) {
            this.dictMap.set(data[0].dictType, data)
            resultDicts.set(data[0].dictType, data)
          }
        }
      })
      return resultDicts
    }
  }
})

export default useDictStore